import React, { useEffect, useState } from 'react';
import { 
  Card, 
  Row, 
  Col, 
  Button, 
  message, 
  Spin, 
  Typography, 
  Divider,
  Avatar,
  Space
} from 'antd';
import { 
  UserOutlined, 
  EditOutlined, 
  LogoutOutlined, 
  ArrowLeftOutlined,
  SafetyOutlined,
  MailOutlined,
  PhoneOutlined,
  IdcardOutlined,
  CrownOutlined
} from '@ant-design/icons';
import RiskPreferenceForm from '../Preference/RiskPreferenceForm';
import RiskPreferenceInfo from '../Preference/RiskPreferenceInfo';
import './UserInfo.scss';
import { useNavigate } from 'react-router-dom';
import { $userLogout } from '../../api/userApi';
import avatarNormal from '../../assets/img/normal.png';
import avatarSilver from '../../assets/img/silver.png';
import avatarGold from '../../assets/img/gold.png';

const getAvatar = (ltv) => {
  if (ltv === '普通用户') return avatarNormal;
  if (ltv === '白银用户') return avatarSilver;
  if (ltv === '黄金用户') return avatarGold;
  return avatarNormal; // 默认头像
};

const { Title, Text } = Typography;

const UserInfo = () => {
  const [userInfo, setUserInfo] = useState(null);
  const [loading, setLoading] = useState(true);
  const [preferences, setPreferences] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    try {
      setLoading(true);
      const storedUserInfo = localStorage.getItem('user_info');
      if (!storedUserInfo) {
        message.error('用户未登录，请先登录');
        navigate('/login');
        return;
      }
      setUserInfo(JSON.parse(storedUserInfo));

      const storedPreferences = localStorage.getItem('investment_preferences');
      if (storedPreferences) {
        setPreferences(JSON.parse(storedPreferences));
        setShowForm(false);
      } else {
        message.info('请先完成风险测评问卷');
        setPreferences(null);
        setShowForm(true);
      }
    } catch (error) {
      message.error('加载信息失败，请刷新页面');
    } finally {
      setLoading(false);
    }
  }, [navigate]);

  const handleEditProfile = () => navigate('/edit-profile');

  const handleLogout = async () => {
    try {
      await $userLogout();
      navigate('/login', { replace: true });
    } catch (error) {
      message.error('注销失败，请重试');
    }
  };

  const handleFormSubmitSuccess = () => {
    const updatedPreferences = localStorage.getItem('investment_preferences');
    if (updatedPreferences) {
      setPreferences(JSON.parse(updatedPreferences));
      setShowForm(false);
      message.success('风险测评完成');
    }
  };

  if (loading) {
    return (
      <div className="loading-container">
        <Spin tip="加载中..." size="large" />
      </div>
    );
  }

  return (
    <div className="user-info-container">
      <Button 
        type="text" 
        icon={<ArrowLeftOutlined />} 
        onClick={() => navigate(-1)}
        className="back-button"
      >
        返回
      </Button>
      
      <Title level={2} className="page-title">我的账户与偏好</Title>
      
      {showForm ? (
        <Card 
          title={
            <Space>
              <SafetyOutlined />
              <span>风险偏好测评</span>
            </Space>
          } 
          bordered={false}
          className="preference-card"
        >
          <Text type="secondary" className="form-description">
            请完成以下风险测评问卷，我们将根据您的风险承受能力提供个性化投资建议
          </Text>
          <RiskPreferenceForm onSubmitSuccess={handleFormSubmitSuccess} />
        </Card>
      ) : (
        <>
          <Row gutter={[24, 24]}>
            <Col xs={24} md={12}>
              <Card
                title="个人信息"
                bordered={false}
                className="profile-card"
              >
                <div className="avatar-section">
                   <img
                    src={getAvatar(userInfo?.ltv)}
                    alt="用户头像"
                    style={{ width: 100, height: 100 }}
                  />
                </div>
                
                <Divider />
                
                <div className="info-section">
                  <div className="info-item">
                    <IdcardOutlined className="info-icon" />
                    <div>
                      <Text type="secondary">用户名</Text>
                      <Text strong className="info-value">{userInfo?.username}</Text>
                    </div>
                  </div>
                  
                  <div className="info-item">
                    <UserOutlined className="info-icon" />
                    <div>
                      <Text type="secondary">昵称</Text>
                      <Text strong className="info-value">{userInfo?.nickname}</Text>
                    </div>
                  </div>
                  
                  <div className="info-item">
                    <MailOutlined className="info-icon" />
                    <div>
                      <Text type="secondary">邮箱</Text>
                      <Text strong className="info-value">{userInfo?.email}</Text>
                    </div>
                  </div>
                  
                  <div className="info-item">
                    <PhoneOutlined className="info-icon" />
                    <div>
                      <Text type="secondary">手机号</Text>
                      <Text strong className="info-value">{userInfo?.phone}</Text>
                    </div>
                  </div>

                <div className="info-item">
                    <CrownOutlined className="info-icon" />
                    <div>
                      <Text type="secondary">等级</Text>
                      <Text strong className="info-value">{userInfo?.ltv}</Text>
                    </div>
                  </div>
                </div>
                
                <Button
                  danger
                  icon={<LogoutOutlined />}
                  onClick={handleLogout}
                  className="logout-button"
                  block
                >
                  注销登录
                </Button>
              </Card>
            </Col>
            
            <Col xs={24} md={12}>
              <Card
                title={
                  <Space>
                    <SafetyOutlined />
                    <span>风险偏好信息</span>
                  </Space>
                }
                bordered={false}
                className="preference-card"
              >
                {preferences ? (
                  <>
                    <RiskPreferenceInfo />
                    <Button
                      type="primary"
                      onClick={() => {
                        localStorage.removeItem('investment_preferences');
                        setPreferences(null);
                        setShowForm(true);
                      }}
                      className="retest-button"
                      style={{ display: 'block', margin: '20px auto' }}
                    >
                      重新测评
                    </Button>
                  </>
                ) : (
                  <>
                    <Text type="secondary">尚未完成风险测评</Text>
                    <Button
                      type="primary"
                      onClick={() => setShowForm(true)}
                      className="start-test-button"
                      style={{ display: 'block', margin: '20px auto' }}
                    >
                      开始测评
                    </Button>
                  </>
                )}
              </Card>
            </Col>
          </Row>
        </>
      )}
    </div>
  );
};

export default UserInfo;